package com.example.smartmedicalsystem.service;

import com.example.smartmedicalsystem.entity.Medicine;
import com.example.smartmedicalsystem.repository.MedicineRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.*;

@Service
@RequiredArgsConstructor
public class AIChatService {
    private final MedicineRepository medicineRepository;
    private final RestTemplate restTemplate = new RestTemplate();

    @Value("${ai.api.url}")
    private String aiApiUrl;

    @Value("${ai.api.key}")
    private String apiKey;

    public String getAIResponse(String message) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
            headers.setBearerAuth(apiKey);

            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-chat");
            requestBody.put("temperature", 0.5);

            List<Map<String, String>> messages = new ArrayList<>();
            messages.add(createMessage("user", message));
            requestBody.put("messages", messages);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<Map> response = restTemplate.exchange(
                    aiApiUrl,
                    HttpMethod.POST,
                    entity,
                    Map.class
            );

            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                Map<String, Object> body = response.getBody();
                if (body.containsKey("choices")) {
                    List<Map<String, Object>> choices = (List<Map<String, Object>>) body.get("choices");
                    if (!choices.isEmpty()) {
                        Map<String, Object> firstChoice = choices.get(0);
                        Map<String, String> messageContent = (Map<String, String>) firstChoice.get("message");
                        return enhanceMedicalResponse(messageContent.get("content"));
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("DeepSeek API调用失败: " + e.getMessage());
        }
        return generateBasicResponse(message);
    }

    private Map<String, String> createMessage(String role, String content) {
        Map<String, String> message = new HashMap<>();
        message.put("role", role);
        message.put("content", content);
        return message;
    }

    private String enhanceMedicalResponse(String aiResponse) {
        List<Medicine> medicines = medicineRepository.findAll();
        StringBuilder responseBuilder = new StringBuilder(aiResponse);
        responseBuilder.append("\n\n系统推荐药品：");
        medicines.forEach(med -> responseBuilder.append(med.getName()).append("、"));
        return responseBuilder.toString().replaceAll("、$", "");
    }

    private String generateBasicResponse(String message) {
        return "已收到您的症状描述：" + message + "，医生将尽快处理";
    }
}